package com.sxmmall.ware.service.impl;

import com.sxmmall.common.constant.WareConstant;
import com.sxmmall.ware.entity.PurchaseDetailEntity;
import com.sxmmall.ware.entity.vo.MergeVo;
import com.sxmmall.ware.entity.vo.PurchaseDoneVo;
import com.sxmmall.ware.entity.vo.PurchaseItemDoneVo;
import com.sxmmall.ware.service.PurchaseDetailService;
import com.sxmmall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxmmall.common.utils.PageUtils;
import com.sxmmall.common.utils.Query;

import com.sxmmall.ware.dao.PurchaseDao;
import com.sxmmall.ware.entity.PurchaseEntity;
import com.sxmmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService; // 库存

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> query = new QueryWrapper<>();
        query.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                query
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // 采购单是否存在
        if (purchaseId == null) {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        // TODO 确认采购单的状态是否可以合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        // 修改采购需求状态
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        // 修改采购单的时间
        this.updateById(purchaseEntity);
    }

    @Override
    @Transactional
    public void receivedPurchase(List<Long> ids) {
        // 1. 确认当前采购单是新建或未分配状态
        List<PurchaseEntity> purchaseList = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());
        // 2. 改变采购单的状态
        this.updateBatchById(purchaseList);
        // 3.改变采购单的状态
        purchaseList.forEach( item ->{
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailEntityList.stream().map(detailEntity -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(detailEntity.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntityList);
        });
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Boolean flag = true;
        List<PurchaseDetailEntity> detailEntityList = new ArrayList<>();
        // 2.改变采购单项的状态
        for (PurchaseItemDoneVo item : purchaseDoneVo.getItems()) {
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
           if (item.getStatus()==WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode()) {
               flag = false;
               purchaseDetail.setStatus(item.getStatus());
           }else{
               purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
               // 3.采购成功入库
               PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
               if (byId!=null){
                   wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
               }
           }
            purchaseDetail.setId(item.getItemId());
            detailEntityList.add(purchaseDetail);
        }
        if (detailEntityList.size()>0){
            purchaseDetailService.updateBatchById(detailEntityList);
        }
        // 1. 改变采购单的状态
        Long id = purchaseDoneVo.getId();
        PurchaseEntity  purchase = new PurchaseEntity();
        purchase.setId(id);
        purchase.setUpdateTime(new Date());
        if (flag){
            purchase.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else{
            purchase.setStatus(WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        }
        this.updateById(purchase);



    }
}